package com.pengtu.web.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.Constants;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.Organization;
import com.pengtu.entity.app.User;
import com.pengtu.entity.project.OwnerOrganization;
import com.pengtu.entity.project.ProjectInfo;
import com.pengtu.model.ProjectModel;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.NumberManager;
import com.pengtu.service.app.AccountManager;
import com.pengtu.service.project.ProjectManager;
import com.pengtu.service.project.SignOrganizationManager;
import com.pengtu.utils.DateUtils;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

@Results({
		@Result(name = BaseActionSupport.RELOAD, location = "projectinfo.action", type = "redirect"),
		@Result(name = BaseActionSupport.NONE, location = "/quality/fproject!view.action?projId=${id}", type = "redirect"),
		@Result(name = "detail", location = "projectinfo!input.action?id=${id}&projectId=${id}", type = "redirect") })
public class ProjectinfoAction extends BaseActionSupport<ProjectInfo> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ProjectManager projManager;
	private SignOrganizationManager signOrgManager;
	private AccountManager accountManager;
	private NumberManager numberManager;

	private String id;
	private ProjectInfo proj;

	private List<ProjectInfo> projectInfoList;
	private OwnerOrganization buildOrg;
	private Organization superviseOrg;
	private Page<ProjectInfo> page = new Page<ProjectInfo>(10);
	private List<OwnerOrganization> ownerList = new ArrayList<OwnerOrganization>();
	private int time;

	private String[] roadTypeList = null;

	public String list() throws Exception {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = projManager.getPageProj(page, queryfilter);
		return SUCCESS;
	}

	/**
	 * 
	 * windows:将所用的工程显示在弹出的窗口中 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String windows() throws Exception {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page.setPageSize(5);
		page = projManager.getPageProj(page, queryfilter);
		return "windows";
	}

	public String input() throws Exception {
		ownerList = signOrgManager.findAllOwner();
		if (StringUtils.isNotEmpty(id)) {
			superviseOrg = proj.getSuperviseCode();
			buildOrg = proj.getOrgCode();
			ProjectModel projectModel =  new ProjectModel();
			projectModel.setProjId(proj.getId());
			projectModel.setProjName(proj.getProjName());
			Struts2Utils.setSessionAttribute("projectModel", projectModel);
		}

		if (StringUtils.isNotEmpty(id)&&"1".equals(proj.getProjKind()))
			roadTypeList = com.pengtu.utils.StringUtils.getItemsForSplit(
					proj.getRaodType(), ",");
		

		// 获得当前年份
		time = DateUtils.getCurrentYear();
		return INPUT;
	}

	/**
	 * 以建设单位查询项目
	 * 
	 * @return
	 * @throws Exception
	 */
	public String info() throws Exception {
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("createDate");
			page.setOrder(Page.DESC);
		}
		page = projManager.getPageProj(page, queryfilter);
		return Constants.INFO;
	}

	/**
	 * 建设单位填写
	 * 
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		User user = SpringSecurityUtils.getCurrentUser();
		if (null != user)
			Struts2Utils.getRequest().setAttribute("organization",
					user.getOrganization());
		return LOGIN;
	}

	/**
	 * 查看
	 * 
	 * @return
	 * @throws Exception
	 */
	public String view() throws Exception {
		ownerList = signOrgManager.findAllOwner();
		return VIEW;
	}

	public void prepareView() throws Exception {
		prepareModel();
	}

	public String save() throws Exception {
		// 建设单位不为空再操作
		if (null != buildOrg) {
			// 如果Id为空,直接添加
			if (StringUtils.isEmpty(id)) {
				OwnerOrganization ownerOrg = signOrgManager.getOwner("id",
						buildOrg.getId());
				if (null != ownerOrg)
					proj.setOrgCode(ownerOrg);
			} else {
				// 如果建设单位发生改变再操作
				if (buildOrg.getId() != proj.getOrgCode().getId()) {
					// 找出对应建设单位
					OwnerOrganization ownerOrg = signOrgManager.getOwner("id",
							buildOrg.getId());
					if (null != ownerOrg)
						proj.setOrgCode(ownerOrg);
				}
			}
		}
		if (null != superviseOrg) {
			if (StringUtils.isEmpty(id)) {
				Organization superOrg = accountManager
						.getOrganization(superviseOrg.getId());
				if (null != superOrg)
					proj.setSuperviseCode(superOrg);
			} else {
				if (superviseOrg.getId() != proj.getSuperviseCode().getId()) {
					Organization superOrg = accountManager
							.getOrganization(superviseOrg.getId());
					if (null != superOrg)
						proj.setSuperviseCode(superOrg);
				}
			}
		}

		if (StringUtils.isEmpty(id)) {
			proj.setStatus("10001");
		}
		proj.setProjCode(numberManager.getprojCode());
		if (null != roadTypeList)
			proj.setRaodType(com.pengtu.utils.StringUtils
					.appendString(roadTypeList));
		projManager.saveOrupdateProj(proj);
		String mes = "";
		if (StringUtils.isNotEmpty(id)) {
			mes = "修改";
		} else {
			mes = "新增";
		}
		addActionMessage(mes + proj.getProjName() + "到项目记录中！");
		if (StringUtils.isNotEmpty(id)) {
			Struts2Utils.sendRefererUrl();
		} else {
			id = proj.getId();
			return "detail";
		}
		return null;
	}

	/**
	 * 建设单位保存项目
	 * 
	 * @return
	 * @throws Exception
	 */
	public String hold() throws Exception {
		addActionMessage("添加" + proj.getProjName() + "到项目记录中！");
		String orgCodeId = Struts2Utils.getParameter("orgCodeId");
		OwnerOrganization owner = signOrgManager.getOwner("id", orgCodeId);
		if (StringUtils.isEmpty(id)) {
			proj.setStatus("10001");
		}
		proj.setOrgCode(owner);
		projManager.saveOrupdateProj(proj);
		return NONE;
	}

	public void prepareHold() throws Exception {
		prepareModel();
	}

	public String delete() throws Exception {
		addActionMessage("删除项目id为：" + id + "的项目！");
		projManager.deleteProj(id);
		return RELOAD;
	}

	protected void prepareModel() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			proj = projManager.getProj("id", id);
		} else {
			proj = new ProjectInfo();
		}
	}
	/**
	 * 验证项目名称是否唯一
	 */
	public void 	findUnByProjName(){
		String oldProjeName = Struts2Utils.getParameter("oldProjName");
		String newProjName = Struts2Utils.getParameter("projName");
		if(projManager.checkProjName(newProjName,oldProjeName)){
			Struts2Utils.renderText("true");
		}else{
			Struts2Utils.renderText("false");
		}
	}

	@Action("/project/api/project")
	public String project() throws Exception {
		QueryFilter filters = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = projManager.getPageProj(page, filters);
		return SUCCESS;
	}

	public String projlist() throws Exception {
		// 获得文本框输入值
		String projName = Struts2Utils.getParameter("q");
		QueryFilter queryfilter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		// 按照类型查找
		queryfilter.addFilter("projName", projName);
		// 从数据库获取符合条件的数据
		List<ProjectInfo> projList = projManager.findListProj(queryfilter);
		// 准备自动补全列表数据
		List<Map<String, Object>> projJson = new ArrayList<Map<String, Object>>();
		Map<String, Object> projMap;
		for (ProjectInfo proj : projList) {
			// 以键值对的形式保存数据
			projMap = new HashMap<String, Object>();
			projMap.put("projId", proj.getId());
			projMap.put("projName", proj.getProjName());
			projJson.add(projMap);
		}
		// 将数据用Json串保存
		Struts2Utils.renderJson(projJson);
		return NONE;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;

	}

	public OwnerOrganization getBuildOrg() {
		return buildOrg;
	}

	public void setBuildOrg(OwnerOrganization buildOrg) {
		this.buildOrg = buildOrg;
	}

	public Organization getSuperviseOrg() {
		return superviseOrg;
	}

	public void setSuperviseOrg(Organization superviseOrg) {
		this.superviseOrg = superviseOrg;
	}

	public List<OwnerOrganization> getOwnerList() {
		return ownerList;
	}

	public Page<ProjectInfo> getPage() {
		return page;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<ProjectInfo> getProjectInfoList() {
		return projectInfoList;
	}

	public void setProjectInfoList(List<ProjectInfo> projectInfoList) {
		this.projectInfoList = projectInfoList;
	}

	@Autowired
	public void setSignOrgManager(SignOrganizationManager signOrgManager) {
		this.signOrgManager = signOrgManager;
	}

	@Autowired
	public void setProjManager(ProjectManager projManager) {
		this.projManager = projManager;
	}

	public ProjectInfo getModel() {
		return proj;
	}

	public int getTime() {
		return time;
	}

	public String[] getRoadTypeList() {
		return roadTypeList;
	}

	public void setRoadTypeList(String[] roadTypeList) {
		this.roadTypeList = roadTypeList;
	}

	@Autowired
	public void setNumberManager(NumberManager numberManager) {
		this.numberManager = numberManager;
	}

}
